package com.m3958.firstgwt.server.ftpserver;

import java.util.HashMap;
import java.util.Map;

import org.apache.ftpserver.ConnectionConfig;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.impl.DefaultConnectionConfig;
import org.apache.ftpserver.listener.ListenerFactory;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;

@Singleton
public class FtpService {
	
	private Map<String, Ftplet> ftplets;
	
	@Inject
	private Injector injector;
	
	
	public void start(){
		FtpServerFactory serverFactory = new FtpServerFactory();
		
		ListenerFactory listenerFactory = new ListenerFactory();
		
		ConnectionConfig cc = new DefaultConnectionConfig(false, 500, 100, 1, 3, 0);
		
        DataConnectionConfigurationFactory dccFactory = new DataConnectionConfigurationFactory();

//        dccFactory.setPassiveAddress(passiveAddress);
        dccFactory.setPassivePorts("22221,22222");
        dccFactory.setActiveEnabled(true);
        dccFactory.setActiveLocalPort(22220);
        DataConnectionConfiguration dcc=dccFactory.createDataConnectionConfiguration();
        
        listenerFactory.setDataConnectionConfiguration(dcc);
		
		serverFactory.setConnectionConfig(cc);
		
		MyFileSystemFactory mfsf = injector.getInstance(MyFileSystemFactory.class);
		
		serverFactory.setFileSystem(mfsf);//gin到此为止断开了.
		
		ftplets = new HashMap<String, Ftplet>();
		
		ftplets.put("myftplet", injector.getInstance(MyFtplet.class));
		
		listenerFactory.setPort(2221);
		
		serverFactory.addListener("default", listenerFactory.createListener());
		
		serverFactory.setUserManager(injector.getInstance(FtpServerUserManager.class));
		
		serverFactory.setFtplets(ftplets);
		FtpServer server = serverFactory.createServer();
		// start the server
		try {
			server.start();
		} catch (FtpException e) {
			e.printStackTrace();
		}
		
	}
}
